package utils

import (
	"bytes"
	"io"
	"net"
)

func SwapData(from, to io.ReadWriteCloser) {
	defer from.Close()
	defer to.Close()

	go TransferData(from, to)
	TransferData(to, from)
}

func TransferData(from io.ReadCloser, to io.WriteCloser) {
	defer from.Close()
	defer to.Close()
	var buffer = make([]byte, 1024)

	for {
		n, err := from.Read(buffer)
		if err != nil {
			break
		}

		n, err = to.Write(buffer[:n])
		if err != nil {
			break
		}
	}
}

func CheckPolicy(conn net.Conn, policy string) bool {
	var buffer = make([]byte, len(policy))
	if len(policy) > 0 {
		n, err := conn.Read(buffer)
		if err != nil {
			return false
		}
		if n != len(policy) {
			return false
		}

		return bytes.Equal(buffer, []byte(policy))
	}
	return false
}
